package com.wenqian.server;

import com.wenqian.server.config.ServerConfig;
import com.wenqian.server.core.RequestHandle;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleHttpServer {
    private final int port;
    private final String webRoot;
    private final ExecutorService threadPool;
    private boolean isRunning = true;

    public SimpleHttpServer(ServerConfig config) {
        this.port = config.getPort();
        this.webRoot = config.getWebRoot();
        this.threadPool = Executors.newFixedThreadPool(config.getPoolSize());
    }

    public void start() {
        try (ServerSocket serverSocket = new ServerSocket(port)){
            System.out.println("服务器启动，监听端口：" + port);
            while (isRunning){
                try{
                    // serverSocket.accept() : 用户连接成功后会返回一个Socket对象，通过这个对象服务器可以和客户端通信
                    Socket clientSocket = serverSocket.accept();
                    System.out.println("接收到新连接：" + clientSocket.getInetAddress());
                    // 将人物提交给线程池
                    threadPool.submit(new RequestHandle(clientSocket, webRoot));
                } catch (IOException e){
                    if (isRunning) {
                        System.err.println("接受连接时出错: " + e.getMessage());
                    }
                }
            }
        } catch (IOException e){
            // IOException 输入输出的异常： 比如端口占用问题，没有权限之类
            if (isRunning) {
                System.err.println("无法启动服务器在端口 " + port + ": " + e.getMessage());
            }
        }
    }

    public void stop() {
        this.isRunning = false;
        if (threadPool != null){
            threadPool.shutdown();
        }
        System.out.println("服务器已停止。");
    }

    public static void main(String[] args) {
        // 从配置文件加载配置
        ServerConfig config = new ServerConfig("server.properties");

        SimpleHttpServer server = new SimpleHttpServer(config);
        server.start();
    }

}
